Кешування у Spring Boot
📌 Використання кешування
Щоб зменшити навантаження на базу даних, можна використовувати кешування.
Spring Boot підтримує кешування за допомогою анотації @Cacheable.
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookService {
private final BookRepository bookRepository;
public BookService(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@Cacheable("books")
public List getAllBooks() {
return bookRepository.findAll();
}
}
🛠 Налаштування кешування
Додаємо залежність у pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
Увімкнення кешування у головному класі:
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableCaching
public class BookStorageApplication {
public static void main(String[] args) {
SpringApplication.run(BookStorageApplication.class, args);
}
}
Назад Далі